let detailComponent = {
    template: `
        <div class="detail page">
            <div class="head">
               <div class="left" @click="back">
                    <span class="iconfont icon-ali-fanhui"></span>
                </div>
                <div class="title"></div>
                <div class="right"></div>
            </div>
            
            <div class="title">
                {{title}}
            </div>
            <div class="author">
                {{author}}
            </div>
            <div class="main">
                <div class="hint" v-show="state===0">
                    <div class="hint-page" v-show="hintIndex === index" v-for="(item,index) in hintList">
                        <p>
                            {{item.text}}
                        </p>
                        <img v-show="item.src" :src="item.src">
                    </div>
                    <div class="btn" @click="nextHint">{{hintIndex>=hintList.length-1?'Start':'Next'}}</div>
                </div>
                <div class="play-ing" v-show="state===1">
                    <div class="section-name">
                        {{section.name}}
                    </div>
                     <div class="play-time">
                        <span class="currentTime">{{parseTime(currentTime)}}</span>
                        
                    </div>
                    <img src="detail/playing.gif">
                </div>
                <div class="finish" v-show="state===2">
                    <template v-if="questionList.length&&!questionState">
                         <div class="questions-title">
                            {{questionName}}
                         </div>
                         <div class="question" v-for="(question,index) in questionList">
                            <div class="question-title">{{index+1}}.{{question.title}}</div>

                             <div class="option" v-for="(option,oi) in question.options">
                                <el-radio v-model="question.answer" :label="option.score">{{option.title}}</el-radio>
                             </div>
                         </div>
                         <el-button style="margin:0 auto;display: block" @click="submit">submit</el-button>
                    </template>
                    <template v-else>
                         The End
                    </template>
                </div>
            </div>
            
            <div class="controls" @touchstart="handleClick" v-show="controlState&&state!==2">
                <div class="click">
                    Click
                </div>
            </div>
        </div>
    `,
    data() {
        return {
            title: null,
            author: null,
            state: 0,
            controlState:false,
            sectionIndex:0,
            sections:[],
            stepIndex:0,
            currentTime:0,
            duration:0,
            finishState:false,
            hintList:[
                {
                    text: 'Please do not drive to attend the class.',
                    src: './detail/tab0.jpg'
                },
                {
                    text: 'Please take care of your toilet or water needs.',
                    src: './detail/tab1.jpg'
                },
                {
                    text: 'Find a safe and quiet place with a good internet connection and sit or lie down comfortably.',
                    src: './detail/tab2.jpg'
                },
                {
                    text: 'You need to listen to the hypnosis recording from beginning to end. If you are interrupted in the middle, be sure to listen to it again as soon as possible to be brought out of the hypnotic state correctly.',
                    src: './detail/tab3.png'
                },
                {
                    text: 'During the entire hypnosis process, one hand should hold the phone as shown in the picture, and keep the index figure on the screen at all times to touch the screen when requested.',
                    src: './detail/tab4.jpg'
                },
                {
                    text: 'If you are ready, hit "Start" with your index figure to start the hypnosis session.',
                }
            ],
            hintIndex:0,
            questionList:[],
            questionName: null,
            questionState:false,
            controlList:[]
        }

    },
    computed: {
        section(){
            return this.sections[this.sectionIndex]?this.sections[this.sectionIndex]:{}
        }
    },
    watch: {},
    mounted() {
        this.playback = new Audio()
        this.playback.onended = ()=>{
            this.processStep(this.stepIndex+1)
        }
        this.playback.oncanplay=()=>{
            this.duration = this.playback.duration
        }
        this.playback.ontimeupdate=()=>{
            this.currentTime = this.playback.currentTime
        }
        this.reminder = new Audio()
        if(this.$route.query.page === 'question' ){
            this.state = 2
        }
        const createSections = (list)=>{
            let sections  = []
            list.forEach((item)=>{
                item.stepList = []
                item.stepList.push({
                    src:rootUrl+item.fragmentUrl,
                    name: item.name,
                    type:"content"
                })
                if(item.conformation){
                    item.stepList.push({
                        src:item.reminderUrl?rootUrl+item.reminderUrl:null,
                        name: item.name,
                        type:'control',
                        timeout:30000
                    })
                }
                sections.push(item)
            })
            this.sections = sections
        }

        this.sessionId = this.$route.query.sessionId
        this.sessionInstances = {
            details:[],
            startTime: parseTime(new Date()),
            sessionId: this.sessionId
        }
        treatmentSession.getItem(this.sessionId).then((session)=>{
            this.title = session.name
            this.author = session.description
            this.questionnaireId = session.questionnaireId
            section.getList({
                sessionId: this.sessionId
            }).then((list)=>{

                sectionFlow.getList(this.sessionId ).then((sortList)=>{
                    let sectionList = []
                    if(sortList.length){
                        sortList.forEach((sort,index)=>{
                            if(index===0){
                                sectionList.push(list.find((item)=>item.id === sort.sectionId))
                            }
                            sectionList.push(list.find((item)=>item.id === sort.nextId))
                        })
                    } else {
                        sectionList = list
                    }

                    createSections(sectionList)
                })

            })

                question.getList(this.sessionId).then((r)=>{
                    this.questionLis = []
                    r.entities.forEach((item)=>{
                        if(item.items){
                            item.items.forEach((question)=>{
                                question.questionnaireId = item.id
                                question.answer = null
                            })
                            this.questionList = this.questionList.concat(item.items)
                        }
                    })
                    // this.questionName = r.name

                })

        })


    },
    activated() {

    },
    methods: {
        submit(){


            let items = []
            this.questionList.forEach((question)=>{
                let itemIndex = items.findIndex(i=>i.questionnaireId === question.questionnaireId)
                if(itemIndex>=0){
                    items[itemIndex].items.push({
                        questionnaireItemId: question.id,
                        option:question.answer,
                        score: question.answer,
                        answer: question.answer

                    })
                } else{
                    items.push({
                        questionnaireId:question.questionnaireId,
                        items: [{
                            questionnaireItemId: question.id,
                            option:question.answer,
                            score: question.answer,
                            answer: question.answer
                        }]
                    })
                }
            })
            items.forEach((item)=>{
                questionInstances.create({
                    questionnaireId:item.questionnaireId,
                    items: item.items
                }).then(()=>{
                    this.questionState=false
                    this.$message.success('submit success!')
                    this.$router.push({
                        name: 'result',
                        query:{
                            sessionId: this.sessionId
                        }
                    })

                })
            })

        },
        nextHint(){
            if(this.hintIndex>=this.hintList.length-1){
                this.start()
            } else {
                this.hintIndex+=1
            }
        },
        parseTime(msTime){
            let time = msTime ;

            let hour = Math.floor(time / 60 / 60);

            hour = hour.toString().padStart(2, "0");

            let minute = Math.floor(time / 60) % 60;

            minute = minute.toString().padStart(2, "0");

            let second = Math.ceil(time) % 60;

            second = second.toString().padStart(2, "0");

            return `${hour}:${minute}:${second}`;
        },
        handleClick(index){
            this.sessionInstances.details.push({
                confirmation: index ? true: false,
                time: parseTime(new Date()),
                sectionId: this.sections[this.sectionIndex].id
            })
            // switch (this.state){
            //     case 0:
            //         this.state = 1
            //         this.controlState = false
            //         this.start()
            //         break
            //     case 1:
                    this.controlState = false
                    this.processStep(this.stepIndex+1)
                    // break
            // }
        },
        back(){
            this.$router.back()
        },
        start(){
            this.state = 1
            this.processSection(0)
        },
        processSection(sectionIndex){
            this.sectionIndex = sectionIndex
            if(this.section.name){
                this.processStep(0)
            }else{
                this.sessionInstances.endTime = parseTime(new Date())
                sessionInstances.create(this.sessionInstances)
                this.state = 2
                this.$message.success('Learning completed!')
            }
        },
        processStep(index) {
            if(this.stepTimer){
                clearTimeout(this.stepTimer)
                this.stepTimer = null
            }
            if(this.controlTimer){
                clearTimeout(this.controlTimer)
                this.controlTimer = null
            }
            if(this.section.stepList&&this.section.stepList[index]){
                this.stepIndex = index
                let step = this.section.stepList[index]
                switch (step.type){
                    case 'content':
                        this.controlState = false
                        this.playAudio(step.src)
                        break
                    case 'control':
                        this.controlState = true
                        this.controlTimer = setTimeout(()=>{
                            if(step.src){
                                this.reminder.src = step.src
                                this.reminder.play()
                            }

                        },step.timeout/2)
                        this.stepTimer = setTimeout(()=>{

                            this.handleClick(index+1)
                        },step.timeout)
                        break
                }
            }else{
                this.processSection(this.sectionIndex+1)
            }
        },
        playAudio(src){

            this.playback.src = src
            this.playback.play()
            this.reminder.pause()
        },
        viewControl(){

        }
    },
    components: {},
    beforeRouteLeave(to, from, next) {
        if(this.playback){
            this.playback.pause()
        }
        if(this.reminder){
            this.reminder.pause()
        }
        if(this.stepTimer){
            clearTimeout(this.stepTimer)
        }
        if(this.controlTimer){
            clearTimeout(this.controlTimer)
        }
        next();
    }
}

